package com.example.studentcoursesysteam.Controller;

import com.example.studentcoursesysteam.Bean.Student;
import com.example.studentcoursesysteam.Repository.CourseRepository;
import com.example.studentcoursesysteam.Repository.StudentCourseRepository;
import com.example.studentcoursesysteam.Repository.StudentRepository;
import com.example.studentcoursesysteam.Repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    CourseRepository courseRepository;
    @Autowired
    StudentCourseRepository studentCourseRepository;
    @Autowired
    TeacherRepository teacherRepository;
    @RequestMapping("/insertStudent")
    public String insertStudent( Student student){
        if (!studentRepository.existsByCode(student.getCode())){
            studentRepository.save(student);
            return "添加成功";
        }else
            return "学号已存在，添加失败";
    }

    @RequestMapping("/updateStudent")
    public String updateStudent( Student student) {
        studentRepository.save(student);
        return "修改成功";
    }

    @RequestMapping("/deleteStudent")
    public String deleteStudent(String code) {
        if(studentRepository.existsByCode(code)){
            studentCourseRepository.deleteStudentId(code);
            studentRepository.getDeleteByCode(code);
            return "删除成功";
        }else
            return "学生不存在，删除失败";
    }


    @RequestMapping("/loginStudent")
    public List<Student> findByLogin(String code, String password){
        return studentRepository.findByCodeAndPassword(code,password);
    }

    @RequestMapping("/selectStudent")
    public Student selectStudent(Integer id){
        Optional<Student> student=studentRepository.findById(id);
        if (student.isPresent())
            return student.get();
        else
            return null;
    }

    @RequestMapping("/selectCode")
    public List<Student> selectCode(String code){
        return studentRepository.findByCode(code);
    }
}
